package com.ittx.dzt.shein.service.semi;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.ittx.dzt.edi.constant.PlatformMessageConstant;
import com.ittx.dzt.edi.dto.PlatformApiParamDTO;
import com.ittx.dzt.edi.dto.StoreConfigDTO;
import com.ittx.dzt.edi.dto.TimeFrameDTO;
import com.ittx.dzt.edi.vo.ResponseMessageVO;
import com.ittx.dzt.shein.constant.SheinSemiApiConstant;
import com.ittx.dzt.shein.handler.AbstractSheinSemiByTimeApiHandler;
import com.ittx.dzt.sys.response.Result;
import lombok.extern.slf4j.Slf4j;
import open.constant.PlatformApiConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 增量下载订单
 * <p>
 * cy.salesOrder.download.byTimeFrame
 * /open-api/order/order-list 请求订单列表 https://open.sheincorp.com/zh/documents/apidoc/detail/3001269
 * </p>
 *
 * @author wl_code@163.com
 * @version 1.0
 * @date 2025/8/4
 */
@Slf4j
@Service
public class SheinSemiSalesOrderDownloadByTimeService extends AbstractSheinSemiByTimeApiHandler<TimeFrameDTO> {

	private static final int DEFAULT_PAGE_SIZE = 30;
	@Autowired
	private SheinSemiSalesOrderDownloadByIdService sheinSemiSalesOrderDownloadByIdService;


	@Override
	public String getMqTopic() {
		return SheinSemiApiConstant.Rocket.SHEIN_SEMI_DOWNLOAD_ORDER_SEARCHLIST_BY_TIME_BATCH_SPLIT_TOPIC;
	}

	@Override
	public String getSheinSemiMethod() {
		return "/open-api/order/order-list";
	}

	@Override
	public String getLocalApiMethod() {
		return PlatformApiConstant.InboundInterface.SALESORDER_DOWNLOAD_BY_TIMEFRAME;
	}

	@Override
	public Result<?> doProcessByNormalType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		//分发数据,异步下载
		Map<String, Boolean> logMap = new HashMap<>();
		return this.requestListBySdk(platformApiParamDTO, timeFrameDTO, logMap);
	}

	@Override
	public Result<?> doProcessByCheckType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		//探查成功时不返回完整数据,只返回数量
		StoreConfigDTO storeConfig = platformApiParamDTO.getStoreConfig();
		return this.requestListBySdk(platformApiParamDTO, timeFrameDTO, null);
	}

	@Override
	public Result<?> doProcessByIdType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		String orderId = platformApiParamDTO.getPlatformIdentifierTag();
		return this.asyncHandlerById(platformApiParamDTO, orderId);
	}

	/**
	 * sdk
	 * 请求平台接口
	 */
	private Result<?> requestListBySdk(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO, Map<String, Boolean> logMap) {
		Map<String, Object> params = new HashMap<>();
		//查询类型：1：根据订单下发时间查询/2：根据订单更新时间查询（当下发订单时会将下发时间同步到更新时间）
		params.put("queryType", 2);
		params.put("startTime", localDateTimeToString(timeFrameDTO.getFrom()));
		params.put("endTime", localDateTimeToString(timeFrameDTO.getTo()));
		params.put("pageSize", DEFAULT_PAGE_SIZE);
		// 查询对应发货仓类型的订单；1:认证仓发货订单/ 2:SHEIN仓发货订单 / 3:商家仓发货订单/ 4: 所有订单；
		// 不传的情况下，巴西商家会返回商家仓发货订单，其他国家市场会返回SHEIN仓发货、商家仓发货订单
		params.put("queryOrderType", 4);
		// 状态过滤,暂时不支持
		// orderStatus
		// 订单状态：1：待处理/ 2：待发货/ 3：待shein发货/ 4：已发货/ 5：已签收/ 6：用户已退款/ 7：待揽收/ 8：已报损/ 9：已拒收
		// List<Integer> statusList = CyUtil.getStatusList(platformApiParamDTO, "sale");
		// params.put("orderStatus", 2);

		// 页码从1开始
		long page = 1;
		// 第一次查询，获取总页数
		params.put("page", page);
		Result<?> result = this.executeApi(platformApiParamDTO.getStoreConfig(), params, platformApiParamDTO.getRequestId());
		if (result.hasError()) {
			return result;
		}
		Map<String, Object> resultMap = (Map<String, Object>) result.getData();
		Map<String, Object> dataMap = (Map<String, Object>) resultMap.get(DATA_FIELD);
		// 订单数量
		int total = Integer.parseInt(dataMap.get(RESULT_TOTAL).toString());
		// 探查模式只返回总数
		if (PlatformApiConstant.ApiByTime.CHECK.equals(platformApiParamDTO.getQueryType())) {
			return Result.success().addData(total);
		}
		Integer totalPage = this.totalPage(total, DEFAULT_PAGE_SIZE);
		if (totalPage > 0) {
			// 倒序查询，防止漏单
			for (int i = totalPage - 1; i >= 1; i--) {
				// 页码从0开始
				params.put("page", i);
				result = this.executeApi(platformApiParamDTO.getStoreConfig(), params, platformApiParamDTO.getRequestId());
				if (result.hasError()) {
					return result;
				}
				resultMap = (Map<String, Object>) result.getData();
				dataMap = (Map<String, Object>) resultMap.get(DATA_FIELD);
				List<Map<String, Object>> list = (List<Map<String, Object>>) dataMap.get("orderList");
				if (CollectionUtil.isNotEmpty(list)) {
					// 分发数据到MQ，异步消费下载
					for (Map<String, Object> order : list) {
						String orderId = order.get("orderNo").toString();
						sendToSplitTopic(platformApiParamDTO, orderId, logMap);
					}
				}
			}
		}
		return Result.success(logMap);
	}

	/**
	 * sdk
	 * 根据单号查询单条订单信息-- 多线程执行
	 */
	@Override
	public Result<?> asyncHandlerById(PlatformApiParamDTO platformApiParamDTO, String orderId) {
		Result<?> result = sheinSemiSalesOrderDownloadByIdService.getOrderById(platformApiParamDTO, orderId);
		if (result.hasError()) {
			return result;
		}
		return this.sendRequestToPlatform(platformApiParamDTO, result.getData(), true);
	}

	/**
	 * 参数校验
	 *
	 * @param platformApiParamDTO 平台请求参数
	 * @param timeFrameDTO        接口请求参数
	 */
	public Result<?> checkParams(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		if (timeFrameDTO == null || platformApiParamDTO.getStoreConfig() == null ||
				timeFrameDTO.getTo() == null || timeFrameDTO.getFrom() == null) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0004_MSG, platformApiParamDTO.getRequestId(),
					this.getPlatformCode(), getLocalApiMethod(), timeFrameDTO);
			log.error(msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0004, msg));
		}
		return Result.success();
	}


}
